package com.kk.license.starter.interceptor;

import com.alibaba.fastjson2.JSON;
import com.kk.license.common.AbstractServerInfos;
import com.kk.license.common.LicenseVerify;
import com.kk.license.common.LinuxServerInfos;
import com.kk.license.common.WindowsServerInfos;
import com.kk.license.common.enums.OsEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangkang
 * @version 1.0
 * @description 证书拦截器
 * @create 2023-07-17 10:17
 */
@Component
@Slf4j
public class LicenseCheckInterceptor implements HandlerInterceptor {

    /**
     * 进入controller层之前拦截请求
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器，验证证书可使用性");
        LicenseVerify licenseVerify = new LicenseVerify();


        //校验证书是否有效
        boolean verifyResult = licenseVerify.verify();

        if (verifyResult) {
            log.info("验证通过，证书可用");
            return true;
        } else {
            log.error("验证失败，证书无效");
            response.setCharacterEncoding("utf-8");
            Map<String, String> result = new HashMap<>(1);
            result.put("result", "您的证书无效，请核查服务器是否取得授权或重新申请证书！");
            //操作系统类型
            String  osName = System.getProperty("os.name").toLowerCase();

            AbstractServerInfos abstractServerInfos = null;

            //根据不同操作系统类型选择不同的数据获取方法
            if (osName.startsWith(OsEnum.WINDOWS.getOsName())) {
                abstractServerInfos = new WindowsServerInfos();
            } else if (osName.startsWith(OsEnum.LINUX.getOsName())) {
                abstractServerInfos = new LinuxServerInfos();
            } else {//其他服务器类型
                abstractServerInfos = new LinuxServerInfos();
            }
            byte[] bytes = JSON.toJSONBytes(abstractServerInfos.getServerInfos());
            byte[] encode = Base64.getEncoder().encode(bytes);
            result.put("machineCode", new String(encode));

            log.error("机器码:{}",new String(encode));

            response.getWriter().write(JSON.toJSONString(result));

            return false;
        }
    }

}
